package com.hlf.common.exception;

import com.hlf.common.utils.ReturnResult;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by Administrator on 2017/9/4.
 * 异常处理器
 */
@RestControllerAdvice
public class BusinessExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public ReturnResult handleRRException(BusinessException e){
        ReturnResult result = new ReturnResult();
        result.put("code", e.getCode());
        result.put("msg", e.getMessage());

        return result;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ReturnResult handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        return ReturnResult.error("数据库中已存在该记录");
    }

    @ExceptionHandler(AuthorizationException.class)
    public ReturnResult handleAuthorizationException(AuthorizationException e){
        logger.error(e.getMessage(), e);
        return ReturnResult.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Exception.class)
    public ReturnResult handleException(Exception e){
        logger.error(e.getMessage(), e);
        return ReturnResult.error();
    }
}
